package com.google.code.hibernate.rest.representation.json;
import static com.google.code.hibernate.rest.representation.json.JSONRepresentor.*;
import com.google.code.hibernate.rest.EntityManager;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.ConverterLookup;
import com.thoughtworks.xstream.core.TreeUnmarshaller;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.mapper.Mapper;

/**
 * 
 * @author wangzijian
 * 
 */
class EntityJSONUnmarshaller extends TreeUnmarshaller {

	private final EntityManager entityManager;
	
	public EntityJSONUnmarshaller(
			Object root, 
			HierarchicalStreamReader reader, 
			ConverterLookup converterLookup, 
			Mapper mapper,
			EntityManager entityManager) {
		super(root, reader, converterLookup, mapper);
		this.entityManager = entityManager;
	}

	@Override
	@SuppressWarnings("rawtypes")
	protected Object convert(Object parent, Class type, Converter converter) {
		Object convert = super.convert(parent, type, converter);
		convertLinkIfNecessary(type, convert);
		return convert;
	}

	@SuppressWarnings("rawtypes")
	private void convertLinkIfNecessary(Class type, Object convert) {
		if (!entityManager.isEntity(type)) {
			return;
		}
		String id = parseId();
		if (id == null) {
			return;
		}
		entityManager.setId(convert, id);
	}

	private String parseId() {
		String href = reader.getAttribute(HREF);
		if (href == null) {
			return null;
		}
		return href.substring(href.lastIndexOf("/") + 1);
	}

}
